import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getPosts } from '../services/api';
import Vote from './Vote';

interface Post {
  ID: number;
  title: string;
  content: string;
  CreatedAt: string;
  upvote_count: number;
  downvote_count: number;
}

export default function BlogSection() {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const response = await getPosts();
        // The backend might return null if there are no posts
        setPosts(response || []);
      } catch (error) {
        console.error('Failed to fetch posts', error);
      }
    };

    fetchPosts();
  }, []);

  return (
    <div className="mx-auto max-w-2xl py-32 sm:py-48 lg:py-56">
      <div className="mx-auto max-w-2xl text-center">
        <h2 className="text-4xl font-semibold tracking-tight text-pretty text-gray-900 sm:text-5xl dark:text-white">From the blog</h2>
        <p className="mt-2 text-lg/8 text-gray-600 dark:text-gray-400">Learn how to grow your business with our expert advice.</p>
      </div>
      <div className="mx-auto mt-10 grid max-w-2xl grid-cols-1 gap-x-8 gap-y-16 border-t border-gray-200 pt-10 sm:mt-16 sm:pt-16 dark:border-gray-700">
        {posts.map((post) => (
          <article key={post.ID} className="flex max-w-xl flex-col items-start justify-between">
            <div className="flex items-center gap-x-4 text-xs">
              <time dateTime={post.CreatedAt} className="text-gray-500 dark:text-gray-400">
                {new Date(post.CreatedAt).toLocaleDateString()}
              </time>
            </div>
            <div className="group relative grow">
              <h3 className="mt-3 text-lg/6 font-semibold text-gray-900 group-hover:text-gray-600 dark:text-white dark:group-hover:text-gray-400">
                <Link to={`/posts/${post.ID}`}>
                  <span className="absolute inset-0" />
                  {post.title}
                </Link>
              </h3>
              <p className="mt-5 line-clamp-3 text-sm/6 text-gray-600 dark:text-gray-400">{post.content}</p>
            </div>
            <div className="mt-4 flex items-center gap-x-4">
              <Vote postId={post.ID} initialUpvotes={post.upvote_count} initialDownvotes={post.downvote_count} />
            </div>
          </article>
        ))}
      </div>
    </div>
  )
}